package com.ujson.uaa.config;

import com.ujson.base.common.config.GlobalConfig;
import com.ujson.uaa.filter.TokenAuthenticationFilter;
import com.ujson.uaa.filter.TokenLoginFilter;
import com.ujson.uaa.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
public class UserWebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private GlobalConfig globalConfig;
    @Autowired
    private JwtUtils jwtUtils;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin().disable() // 禁用表单登录
            .authorizeRequests() // 设置哪些不需要授权
            .antMatchers(
                    "/v2/api-docs",
                    "/swagger-resources/configuration/ui",
                    "/swagger-resources",
                    "/swagger-resources/configuration/security",
                    "/swagger-ui.html",
                    "/images/**",
                    "/swagger-ui.html",
                    "/webjars/**",
                    "**/favicon.ico",
                    "/css/**",
                    "/js/**",
                    "/login",
                    "/logout",
                    "/register",
                    "/web/api/v1/token/*"
            ).permitAll()
            .anyRequest().authenticated()// 设置哪些需要授权
            .and()
            .addFilter(new TokenLoginFilter("/login", jwtUtils, authenticationManager()))
            .addFilter(new TokenAuthenticationFilter(globalConfig, jwtUtils, authenticationManager()))
            .csrf().disable()
        ;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().mvcMatchers("/register", "/admin/pass");
    }

}
